package com.bw.p19.login

import androidx.lifecycle.viewModelScope
import com.bw.base.entity.CodeSendEntity
import com.bw.base.entity.LoginEntity
import com.bw.base.entity.Res
import com.bw.base.entity.UserInfoEntity
import com.bw.base.mvvm.BaseViewModel
import com.bw.base.utils.SingleLiveData
import kotlinx.coroutines.launch
import retrofit2.http.Query

class LoginViewModel:BaseViewModel() {
    //获取验证码
    val codeSendSuccess = SingleLiveData<Res<CodeSendEntity>>()
    val codeSendFail = SingleLiveData<String>()

    fun codeSend(@Query("phone")phone:String){
        viewModelScope.launch {
            try {
                codeSendSuccess.postValue(apiService.codeSend(phone))
            }catch (e:Exception){
                codeSendFail.postValue(e.message.toString())
            }
        }
    }


    val loginCodeSuccess = SingleLiveData<Res<LoginEntity>>()
    val loginCodeFail = SingleLiveData<String>()
    fun loginCode(captcha:String,phone: String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["captcha"] = captcha
                map["phone"] = phone
                loginCodeSuccess.postValue(apiService.loginCode(mapToBody(map)))
            }catch (e:Exception){
                loginCodeFail.postValue(e.message.toString())
            }
        }
    }
    //获取用户信息
    val userInfoSuccess = SingleLiveData<Res<UserInfoEntity>>()
    val userInfoFail = SingleLiveData<String>()
    fun userInfo(){
        viewModelScope.launch {
            try {
                userInfoSuccess.postValue(apiService.userInfo())
            }catch (e:Exception){
                userInfoFail.postValue(e.message.toString())
            }
        }
    }
    //修改密码
    val updatePwdSuccess = SingleLiveData<Res<Boolean>>()
    val updatePWdFail = SingleLiveData<String>()
    fun updatePWd(account:String,captcha:String,password:String){
        viewModelScope.launch {
            try {
                val map = HashMap<String,Any>()
                map["account"] = account
                map["captcha"] = captcha
                map["password"] = password
                updatePwdSuccess.postValue(apiService.updatePwd(mapToBody(map)))
            }catch (e:Exception){
                updatePWdFail.postValue(e.message.toString())
            }
        }

    }
}